package loader;

import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;

import loader.parser.Parser;
import loader.parser.adapter.SiteAdapter;
import loader.persister.CityPersister;
import loader.persister.DealPersister;
import loader.persister.Persister;

public class Loader {

	private Persister persister;

	public static void main(String[] args) {

		Properties prop = System.getProperties();
		prop.setProperty("http.proxyHost", "10.132.145.24");
		prop.setProperty("http.proxyPort", "808");

		Loader loader = new Loader();
		Persister persister = new DealPersister();
		persister.clear();
		loader.setPersister(persister);
		loader.load("beijing");

		try {
			persister.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println(new Date());
	}

	public void load(String city) {
		System.out.println("loading city(meituan):"+ city);
		this.load("meituan", city);
		System.out.println("loading city(wowotuan):"+ city);
		this.load("wowotuan", city);
	}

	public void load(String siteName, String city) {
		
		System.out.println(city);
		
		SiteAdapter adapter = Configuration.getAdapter(siteName);
		String url = adapter.getFullUrl(city);
		this.persister.setAdapter(adapter);
		Parser parser = new Parser(this.getPersister());

		// FilePuller puller = new FilePuller();
		// String dir = adapter.getFileDir();
		// puller.pull(url, dir);
		// parser.parse(dir);

		try {
			parser.parse(new URL(url));
		} catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
		}
	}
	
	public void loadCities(String siteName){
		SiteAdapter adapter = Configuration.getAdapter(siteName);
		Persister persister = new CityPersister(adapter);
		persister.clear();
	
		Parser parser = new Parser(persister);
		try {
			parser.parse(new URL(adapter.getCitiesUrl()));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			persister.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void setPersister(Persister persister) {
		this.persister = persister;
	}

	public Persister getPersister() {
		return persister;
	}
}
